let _Vue = null;
export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;

    _Vue = Vue;

    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$router.init();
        }
      },
    });
  }
  constructor(options) {
    this.options = options;
    this.mode = this.options.mode || 'hash';
    this.data = _Vue.observable({
      current: this.mode === 'history' ? '/' : '/#',
    });
    this.routeMap = {};
  }
  init() {
    this.createRouterMap();
    this.initComponents(_Vue);
    this.initEvent();
  }
  createRouterMap() {
    this.options.routes.forEach(route => {
      if (this.mode === 'history') {
        this.routeMap[route.path] = route.component;
      } else if (this.mode === 'hash') {
        this.routeMap['#' + route.path] = route.component;
      }
    });
  }
  initComponents(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h(
          'a',
          {
            attrs: {
              href: this.to,
            },
            on: {
              click: this.handleClick,
            },
          },
          [this.$slots.default]
        );
      },
      methods: {
        handleClick(e) {
          const mode = this.$router.mode;
          if (mode === 'history') {
            history.pushState({}, '', this.to);
          } else if (mode === 'hash') {
            location.hash = this.to;
          }
          this.$router.data.current = this.to;
          e.preventDefault();
        },
      },
    });
    Vue.component('router-view', {
      render(h) {
        const router = this.$router;
        const component = router.routeMap[router.data.current];
        return h(component);
      },
    });
  }
  initEvent() {
    if (this.mode === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname;
      });
    } else if (this.mode === 'hash') {
      window.addEventListener('hashchange', () => {
        console.log(123);
        this.data.current = window.location.hash;
      });
    }
  }
}
